from flask import Blueprint, abort, request
from orm.user import User

bp = Blueprint('user', __name__)


@bp.route('/Login/<user>', methods=['POST'])
def login(user):
    if user is None:
        return 'Error'
    password = request.data.decode('utf-8')
    print(password)
    if password is None:
        return 'Error'
    try:
        login_user = User.select().where(User.name == user).get()
        print(login_user.name, login_user.password)
        if login_user is None:
            return "Error"
        if login_user.password == password:
            return str(login_user.uid)
        else:
            return 'Error'
    except Exception:
        return 'Error'


@bp.route('/Register/<user>', methods=['POST'])
def register(user):
    if user is None:
        return 'Error'
    password = request.data.decode('utf-8')
    if password is None:
        return 'Error'
    try:
        register_user = User.select().where(User.name == user).get()
        return 'Existed'
    except Exception:
        register_user = User.create(name=user, password=password)
        return str(register_user.uid)
